package com.eqdd.yiqidian.ui.gongneng.renshi.train

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.widget.TextView
import com.bigkoo.pickerview.OptionsPickerView
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.rebuild.InviteCareerListResultBean
import com.eqdd.yiqidian.bean.rebuild.TrainListBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditHintBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditOtherBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimTimeSelectBean
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.kotlin.BaseAddActivity
import com.eqdd.yiqidian.kotlin.bottomDialog
import com.eqdd.yiqidian.kotlin.timePicker
import com.eqdd.yiqidian.kotlin.toArrayList
import com.eqdd.yiqidian.kotlin.utils.TimePickerUtil
import com.eqdd.yiqidian.ui.MultiSelectListActivity
import com.eqdd.yiqidian.ui.base.EditTextActivity
import com.eqdd.yiqidian.ui.select.SelectTrainActivity
import com.eqdd.yiqidian.ui.select.SelectTwoDeepMultiTagActivity
import com.eqdd.yiqidian.utils.SelectUtil
import com.eqdd.yiqidian.utils.SplitUtil
import com.lzy.okgo.model.HttpParams
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by jhj on 18-9-11.
 */
class TrainRequestAddActivity : BaseAddActivity() {

    private var selectedList: ArrayList<InviteCareerListResultBean>? = arrayListOf()
    private val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
    private var optionsPicker: OptionsPickerView<*>? = null
    private var zodiac: String? = null
    private var banZodiac: String? = null
    private var trainBean: TrainListBean? = null
    private var type: Int = 0


    override val title: String
        get() = "培训需求"
    override val url: String
        get() = HttpConfig.BASE_URL + HttpConfig.TRAIN_REQUEST_ADD

    override fun uploadParams(): HttpParams {
        val params = HttpParams()
        val bean = slimAdapterEx.data
        val array = bean[19].content?.split("～")
        if (array?.size == 2) {
            params.put("lecturerMinAge", array[0])//lecturerMaxAge
            params.put("lecturerMaxAge", array[1])//lecturerMaxAge
        } else {
            params.put("lecturerMinAge", 18)//lecturerMaxAge
            params.put("lecturerMaxAge", 65)//lecturerMaxAge
        }
        params.put("contacts", user.guid)
        params.put("theTheme", bean[1].content)
        params.put("theCategory", bean[2].content)
        params.put("trainees", bean[3].content)
        params.put("thedateStart", bean[4].content)
        params.put("thedateEnd", bean[5].content)
        params.put("theplace", bean[6].content)
        params.put("budgetedExpense", bean[7].content)
        params.put("keywords", bean[8].content)
        params.put("otherDemand", bean[9].content)

        params.put("comName", bean[11].content)
        params.put("contactsName", bean[12].content)
        params.put("phone", bean[13].content)
        params.put("handset", bean[14].content)
        params.put("qq", bean[15].content)

        params.put("lecturerIndustry", bean[17].content ?: "不限")
        params.put("lecturerSex", getSex(bean[18].content))
        params.put("lecturerShuXiang", bean[20].content ?: "不限")
        params.put("lecturerJinJIShuXiang", bean[21].content ?: "不限")
        params.put("lecturerAddress", bean[22].content ?: "不限")
        params.put("lecturerEducation", bean[23].content ?: "不限")
        params.put("lecturerMagor", bean[24].content ?: "不限")
        params.put("lecturerZhiCheng", bean[25].content ?: "不限")
        params.put("lecturerLanguages", bean[26].content ?: "不限")
        params.put("lecturerWorkBackground", bean[27].content ?: "不限")
        params.put("lecturerPost", bean[28].content ?: "不限")
        params.put("applyId", trainBean?.id ?: 0)

        return params
    }

    private fun getSex(content: String?): Int {
        if (content == "男") {
            return 1
        } else if (content == "女") {
            return 2
        } else {
            return 0
        }
    }


    override fun itemClick(p: Int) {
        when (p) {
            1 -> {
                if (type == 1) {
                    startActivityForResult<SelectTrainActivity>(1)
                }
            }
            2 -> {
                startActivityForResult<SelectTwoDeepMultiTagActivity>(2, Config.OPTION to 45, Config.MAX_NUM to 5)
            }
            3 -> {
                SelectUtil.selectPostFromCom(this, selectedList?.toArrayList())
            }
            4 -> {
                val startTime = slimAdapterEx.getDataItem(4).content
                val endTime = slimAdapterEx.getDataItem(5).content
                timePicker(getDate(startTime), getDate(endTime), TimePickerUtil.type2, true, body = {
                    slimAdapterEx.getDataItem(4).content = sdf.format(it)
                    slimAdapterEx.notifyItemChanged(4)
                })
            }
            5 -> {
                val startTime = slimAdapterEx.getDataItem(4).content
                val endTime = slimAdapterEx.getDataItem(5).content
                timePicker(getDate(startTime), getDate(endTime), TimePickerUtil.type2, false, body = {
                    slimAdapterEx.getDataItem(5).content = sdf.format(it)
                    slimAdapterEx.notifyItemChanged(5)
                })
            }
            7 -> {
                val money = slimAdapterEx.getDataItem(7).content
                startActivityForResult<EditTextActivity>(7, "title" to "培训预算/元",
                        "tip" to "培训预算/元", "content" to money, "onlyNumber" to true)
            }
            17 -> {
                startActivityForResult<SelectTwoDeepMultiTagActivity>(17, Config.OPTION to 45, Config.MAX_NUM to 5)
            }
            18 -> {
                val list = arrayListOf("男", "女", "不限")
                bottomDialog(list) {
                    slimAdapterEx.getDataItem(18).content = list[it - 1]
                    slimAdapterEx.notifyItemChanged(18)
                }
            }
            19 -> {
                option(slimAdapterEx.getDataItem(19).content) {
                    slimAdapterEx.getDataItem(19).content = it
                    slimAdapterEx.notifyItemChanged(19)
                }
            }
            20 -> {
                val list = resources.getStringArray(R.array.zodiac)
                startActivityForResult<MultiSelectListActivity>(20, Config.TITLE to "属相", "data" to list, "select" to zodiac)
            }
            21 -> {
                val list = resources.getStringArray(R.array.zodiac)
                startActivityForResult<MultiSelectListActivity>(21, Config.TITLE to "属相", "data" to list, "select" to banZodiac)
            }
        }
    }


    override fun setEditBeans() {
        type = intent.getIntExtra(Config.TYPE, 0)
        datas.add(SlimEditOtherBean("培训信息", 0))
        if (type == 1) {
            datas.add(SlimEditEnterBean("*培训主题", trainBean?.theTheme, 1, "请选择").setDeal(true).setNeed(true))
            datas.add(SlimEditHintBean("*培训类别", trainBean?.theCategory, 2).setNeed(true))
            datas.add(SlimEditHintBean("*培训对象", trainBean?.trainees, 3).setNeed(true))
        } else {
            datas.add(SlimEditEnterBean("*培训主题", "", 1, "请输入").setNeed(true))
            datas.add(SlimEditEnterBean("*培训类别", "", 2, "请选择").setDeal(true).setNeed(true))
            datas.add(SlimEditEnterBean("*培训对象", "", 3, "请选择").setDeal(true).setNeed(true))
        }
        datas.add(SlimTimeSelectBean("*培训开始时间", trainBean?.thedateStart, 4, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimTimeSelectBean("*培训结束时间", trainBean?.thedateEnd, 5, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("*培训地点", "", 6, "请输入").setNeed(true))
        datas.add(SlimEditEnterBean("*培训预算/元", trainBean?.budgetedExpense?.toString(), 7, "请输入").setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("关键词", "", 8, "请输入"))
        datas.add(SlimEditEnterBean("其他要求", "", 9, "请输入"))
        datas.add(SlimEditOtherBean("联系方式", 10))
        datas.add(SlimEditEnterBean("*公司名称", user.company, 11, "请输入").setNeed(true))
        datas.add(SlimEditEnterBean("*联系人", user.username, 12, "请输入").setNeed(true))
        datas.add(SlimEditEnterBean("电话", "", 13, "请输入"))
        datas.add(SlimEditEnterBean("手机", user.uname, 14, "请输入"))
        datas.add(SlimEditEnterBean("QQ", "", 15, "请输入"))
        datas.add(SlimEditOtherBean("对讲师的要求", 16))
        datas.add(SlimEditEnterBean("行业要求", null, 17, "请选择").setDeal(true))
        datas.add(SlimEditEnterBean("性别要求", null, 18, "请选择").setDeal(true))
        datas.add(SlimEditEnterBean("年龄要求", null, 19, "请选择").setDeal(true))
        datas.add(SlimEditEnterBean("属相要求", null, 20, "请选择").setDeal(true))
        datas.add(SlimEditEnterBean("禁忌属相", null, 21, "请选择").setDeal(true))
        datas.add(SlimEditEnterBean("常驻地址要求", null, 22, "请输入"))
        datas.add(SlimEditEnterBean("学历要求", null, 23, "请输入"))
        datas.add(SlimEditEnterBean("所学专业", null, 24, "请输入"))
        datas.add(SlimEditEnterBean("职称要求", null, 25, "请输入"))
        datas.add(SlimEditEnterBean("外语授课要求", null, 26, "请输入"))
        datas.add(SlimEditEnterBean("工作背景要求", null, 27, "请输入"))
        datas.add(SlimEditEnterBean("担当职务要求", null, 28, "请输入"))

        slimAdapterEx.register(R.layout.list_item_29, SlimInjector<SlimTimeSelectBean> { data, injector ->
            injector?.text(R.id.tv_left_content, data?.title)
                    ?.text(R.id.tv_right_content, data?.content)
                    ?.hint(R.id.tv_right_content, data?.hint)
                    ?.with<TextView>(R.id.tv_left_content) {
                        if (dealText(data?.title).indexOf("*") == 0) {
                            val spannableStringBuilder = SpannableStringBuilder(dealText(data?.title))
                            val foregroundColorSpan = ForegroundColorSpan(Color.RED)
                            spannableStringBuilder.setSpan(foregroundColorSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                            it.text = spannableStringBuilder
                        } else {
                            it.text = dealText(data?.title)
                        }
                    }
        })
        slimAdapterEx.register(R.layout.item_edit_title_type, SlimInjector<SlimEditOtherBean> { data, injector ->
            injector?.text(R.id.tv_top_title, data?.title)
        })


    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                20 -> {
                    zodiac = data?.getStringExtra("data")
                    datas[20].content = zodiac
                    slimAdapterEx.notifyItemChanged(20)
                }
                21 -> {
                    zodiac = data?.getStringExtra("data")
                    datas[21].content = zodiac
                    slimAdapterEx.notifyItemChanged(21)
                }
            }
        } else if (resultCode == Config.SUCCESS) {
            when (requestCode) {
                2 -> {
                    val tags = data?.getStringArrayListExtra(Config.STRING_LIST)
                    slimAdapterEx.getDataItem(2).content = SplitUtil.combin(tags, ",")
                    slimAdapterEx.notifyItemChanged(2)
                }
                17 -> {
                    val tags = data?.getStringArrayListExtra(Config.STRING_LIST)
                    slimAdapterEx.getDataItem(17).content = SplitUtil.combin(tags, ",")
                    slimAdapterEx.notifyItemChanged(17)
                }
                Config.SELECT_POST_FROM_COM -> {
                    selectedList = data?.getParcelableArrayListExtra<InviteCareerListResultBean>(Config.LIST)
                    val postStrs = SplitUtil.combin(selectedList, ",", "name")
                    slimAdapterEx.getDataItem(3).content = postStrs
                    slimAdapterEx.notifyItemChanged(3)
                }
                1 -> {
                    trainBean = data?.getSerializableExtra(Config.BEAN) as TrainListBean
                    val indexStart = if (trainBean?.thedateStart?.indexOf("T") == -1) {
                        trainBean?.thedateStart?.length
                    } else {
                        trainBean?.thedateStart?.indexOf("T")
                    }
                    val indexEnd = if (trainBean?.thedateEnd?.indexOf("T") == -1) {
                        trainBean?.thedateEnd?.length
                    } else {
                        trainBean?.thedateEnd?.indexOf("T")
                    }

                    slimAdapterEx.getDataItem(1).content = trainBean?.theTheme
                    slimAdapterEx.getDataItem(2).content = trainBean?.theCategory
                    slimAdapterEx.getDataItem(3).content = trainBean?.trainees
                    slimAdapterEx.getDataItem(4).content = trainBean?.thedateStart?.substring(0, indexStart
                            ?: 0)
                    slimAdapterEx.getDataItem(5).content = trainBean?.thedateEnd?.substring(0, indexEnd
                            ?: 0)
                    slimAdapterEx.getDataItem(7).content = trainBean?.budgetedExpense?.toString()
                    slimAdapterEx.notifyItemChanged(1)
                    slimAdapterEx.notifyItemChanged(2)
                    slimAdapterEx.notifyItemChanged(3)
                    slimAdapterEx.notifyItemChanged(4)
                    slimAdapterEx.notifyItemChanged(5)
                    slimAdapterEx.notifyItemChanged(7)
                    slimAdapterEx.notifyDataSetChanged()

                }
            }
        } else if (resultCode == Config.INTENT_CONTENT) {
            val content = data?.getStringExtra("content")
            when (requestCode) {
                7 -> {
                    slimAdapterEx.getDataItem(7).content = content
                    slimAdapterEx.notifyItemChanged(7)
                }
            }
        }

    }


    fun getDate(string: String?): Date? {
        if (string.isNullOrBlank()) {
            return null
        }
        return sdf.parse(string)
    }


    fun option(string: String?, body: (string: String) -> Unit) {
        var p1 = 0
        var p2 = 0
        val list = (18..65).toList()
        if (!string.isNullOrBlank()) {
            val array = string?.split("～")
            p1 = if (list.indexOf(array?.get(0)?.toInt()) != -1) list.indexOf(array?.get(0)?.toInt()) else 0
            p2 = if (list.indexOf(array?.get(1)?.toInt()) != -1) list.indexOf(array?.get(1)?.toInt()) else 0
        }
        if (optionsPicker == null) {
            optionsPicker = OptionsPickerView
                    .Builder(this, OptionsPickerView.OnOptionsSelectListener { options1, options2, options3, v ->
                        if (options1 > options2) {
                            toast("年龄选择不合法")
                            return@OnOptionsSelectListener
                        }
                        body(String.format(Locale.CHINA, "%d～%d", list[options1], list[options2]))
                    })
                    .setOutSideCancelable(true)
                    .build()
            optionsPicker?.setNPicker(list, list, null)
        }
        optionsPicker?.setSelectOptions(p1, p2)
        optionsPicker?.show()
    }
}